//
//  WKScanCodeViewController.m
//  ourToken
//
//  Created by wakeup on 2018/6/14.
//  Copyright © 2018年 ourtoken. All rights reserved.
//

#import "WKScanCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "WKBaseHeader.h"

@interface WKScanCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate, AVCaptureVideoDataOutputSampleBufferDelegate>

@property (nonatomic, strong) UIView *backView;//底色view

@property (nonatomic, strong) WKScanView *scanView;//扫描的view

@property (strong, nonatomic) AVCaptureSession *session;//捕获事件相关的会话

@end

@implementation WKScanCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationView];
    [self.scanView stratScanLineAnimation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    
    // 校验相机权限
    [WKSystemPermissionsManager checkCameraAuthorizationStatusWithGrand:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setCode];
            });
        }
    }];
}

- (void)setNavigationView {
    [super setNavigationView];
    self.navigationView.topTitleLabel.text = @"二维码";
    self.navigationView.topTitleLabel.textColor = [UIColor whiteColor];
    self.navigationView.backgroundColor = [UIColor blackColor];
    self.navigationView.alpha = 0.8;
    self.navigationView.topLineView.backgroundColor = [UIColor blackColor];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self.view addSubview:self.backView];
    [self.view addSubview:self.scanView];
}

- (void)setCode {
    
    CGFloat width = AppManager.scanView_WH/AppManager.width;
    CGFloat height = AppManager.scanView_WH/(AppManager.height-AppManager.navigationHeight);
    CGFloat x = (AppManager.width-AppManager.scanView_WH)/2/AppManager.width;
    CGFloat y = (AppManager.height-AppManager.scanView_WH-AppManager.navigationHeight)/2/AppManager.height;
    
    self.session = [[AVCaptureSession alloc] init];
    //添加一个预览图层, 用来查看摄像头的内容
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    //设置这种填充方式，才能准确设置frame
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = CGRectMake(0, 0, AppManager.width, AppManager.height-AppManager.navigationHeight);
    [self.backView.layer insertSublayer:layer atIndex:0];
    
    //创建设备输入,绑定摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if ([self.session canAddInput:deviceInput]) {
        [self.session addInput:deviceInput];
    }
    
    //闪光灯
    AVCaptureVideoDataOutput *videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
    [videoDataOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
    if ([self.session canAddOutput:videoDataOutput]) {
        [self.session addOutput:videoDataOutput];
    }
    
    //将输出添加到会话(元数据输出)
    AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
    //解析结果通过代理进行回调
    [metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    if ([self.session canAddOutput:metadataOutput]) {
        [self.session addOutput:metadataOutput];
    }
    
//    //查找可以解析的数据类型
//    NSArray <NSString *> *types = [metadataOutput availableMetadataObjectTypes];
//    DLog(@"types : %@", types);
//    //解析成什么类型的数据
//    metadataOutput.metadataObjectTypes = @[@"org.iso.QRCode"];
    
    metadataOutput.metadataObjectTypes = [WKSystemPermissionsManager metadataObjectTypesWithType:WKScannerTypeBoth];
    
    //配置有效的扫描范围(0.0 ~ 1.0)
    metadataOutput.rectOfInterest = CGRectMake(x, y, height, width);
    
    [self.session startRunning];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
//解析到数据时触发的代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    AVMetadataMachineReadableCodeObject *codeObj = metadataObjects.lastObject;
    NSString *string = codeObj.stringValue;
    DLog(@"%@", string);
    [self.session stopRunning];
    
    WKTransferViewController *transfer = [[WKTransferViewController alloc] init];
    [self.navigationController pushViewController:transfer animated:YES];
}

#pragma mark -- AVCaptureVideoDataOutputSampleBufferDelegate
//实时监听亮度值
- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    
    CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
    NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
    CFRelease(metadataDict);
    NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
    
    //亮度值
    float brightnessValue = [[exifMetadata objectForKey:(NSString *)kCGImagePropertyExifBrightnessValue] floatValue];
    
    DLog(@"亮度值=%f",brightnessValue);
    
    if (!self.scanView.flashlightBtn.selected) {
        if (brightnessValue < -1.0) {
            [self.scanView showFlashlightWithAnimated:YES];
        }else
        {
            [self.scanView hideFlashlightWithAnimated:YES];
        }
    }
}

#pragma mark - App从后台进入前台
- (void)appDidBecomeActive:(NSNotification *)notify {
    if (self.session) {
        [self.session startRunning];
        [self.scanView stratScanLineAnimation];
    }
}

#pragma mark - App从前台进入后台
- (void)appWillResignActive:(NSNotification *)notify {
    [self.scanView setFlashlightOn:NO];
    if (self.session) {
        [self.session stopRunning];
        [self.scanView pauseScanLineAnimation];
    }
}

#pragma mark - 懒加载UI
- (UIView *)backView {
    if (_backView == nil) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, AppManager.navigationHeight, AppManager.width, AppManager.height-AppManager.navigationHeight)];
        _backView.backgroundColor = [UIColor blackColor];
    }
    return _backView;
}

- (WKScanView *)scanView {
    if (_scanView == nil) {
        _scanView = [[WKScanView alloc] initWithFrame:CGRectMake(0, AppManager.navigationHeight, AppManager.width, AppManager.height-AppManager.navigationHeight)];
    }
    return _scanView;
}

@end
